package handlers

import (
	json2 "encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"nxs/cache"
	"nxs/models"
	"nxs/pkg"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "用户名或密码为空",
		})
		return
	}
	redis_login_key := "login_error_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_login_key).Int()
	if errCount >= 3 {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "密码错误三次,禁止登录",
		})
		return
	}
	var user models.User
	models.DB.Where("username=?", username).First(&user)
	if user.ID == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_login_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_login_key, 3, time.Hour*2)
			c.JSON(http.StatusOK, gin.H{
				"code": 500,
				"msg":  "密码错误三次,封禁两小时",
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登陆成功",
	})
	return
}

func List(c *gin.Context) {
	var nxs []models.Nxs

	redis_list_key := "data_list"
	cacheJson, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()
	if cacheJson == "" {
		models.DB.Find(&nxs)
		json, _ := json2.Marshal(nxs)
		cache.Rdb.Set(cache.Ctx, redis_list_key, json, time.Hour*2)
	} else {
		json2.Unmarshal([]byte(cacheJson), &nxs)
	}
	models.DB.Find(&nxs)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": nxs,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var nxs models.Nxs

	redis_detail_key := "data_detail" + id
	cacheJson, _ := cache.Rdb.Get(cache.Ctx, redis_detail_key).Result()
	if cacheJson == "" {
		models.DB.Where("id=?", id).First(&nxs)
		json, _ := json2.Marshal(nxs)
		cache.Rdb.Set(cache.Ctx, redis_detail_key, json, time.Hour*2)
	} else {
		json2.Unmarshal([]byte(cacheJson), &nxs)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": nxs,
	})
	return
}
